package com.soft.springhrms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soft.springhrms.mapper.EmployeesMapper;
import com.soft.springhrms.pojo.Attendance;
import com.soft.springhrms.pojo.Employees;
import com.soft.springhrms.service.AttendanceService;
import com.soft.springhrms.mapper.AttendanceMapper;
import com.soft.springhrms.vo.AttendanceVO;
import com.soft.springhrms.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author DELL
 * @description 针对表【attendance】的数据库操作Service实现
 * @createDate 2024-11-16 18:48:17
 */
@Service
public class AttendanceServiceImpl extends ServiceImpl<AttendanceMapper, Attendance>
        implements AttendanceService {
    @Autowired
    private AttendanceMapper attendanceMapper;
    @Autowired
    private EmployeesMapper employeesMapper;
    @Override
    @Async
    public ResultVO clockInRequest() {
        List<Employees> employeesList = employeesMapper.selectEmployeesList();
        for(Employees employees : employeesList) {
            Attendance attendance = new Attendance();
            attendance.setEmployeeId(employees.getId());
            attendance.setClockInType("上班打卡");
            attendance.setCreatedAt(new Date());
            attendance.setAttendanceStatus("未打卡");
            attendanceMapper.insert(attendance);
        }
        try {
            updateAttendanceStatusAfterDelay();
        }catch (Exception e){
            e.printStackTrace();
            return ResultVO.error(409,"开启定时任务失败");
        }
        return ResultVO.success("成功发送打卡请求","成功发送打卡请求");
    }
    @Async
    @Override
    public ResultVO clockOutRequest() {
        List<Employees> employeesList = employeesMapper.selectEmployeesList();
        for(Employees employees : employeesList) {
            Attendance attendance = new Attendance();
            attendance.setEmployeeId(employees.getId());
            attendance.setClockInType("下班打卡");
            attendance.setCreatedAt(new Date());
            attendance.setAttendanceStatus("未打卡");
            attendanceMapper.insert(attendance);
        }
        try {
            updateAttendanceStatusAfterDelay();
        }catch (Exception e){
            e.printStackTrace();
            return ResultVO.error(409,"开启定时任务失败");
        }
        return ResultVO.success("成功发送打卡请求","成功发送打卡请求");
    }

    @Override
    public IPage<AttendanceVO> getAttendanceCount(int page, int size) {
        Page<AttendanceVO> attendanceVOPage = new Page<>(page, size);
        return attendanceMapper.getAttendanceCount(attendanceVOPage);
    }

    @Override
    public Integer changeEmployeeAttendanceStatus(String clockTime, Integer id, String attendanceStatus) {
        return attendanceMapper.changeEmployeeAttendanceStatus(clockTime,id,attendanceStatus);
    }

    @Override
    public ResultVO getAbsenceCount(Integer employeeId) {
        // 获取当月的第一天和最后一天
        LocalDate now = LocalDate.now();
        LocalDate startOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());
        LocalDate endOfMonth = now.with(TemporalAdjusters.lastDayOfMonth());
        QueryWrapper queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("employee_id", employeeId);
        queryWrapper.eq("attendance_status","缺勤");
        queryWrapper.between("created_at", startOfMonth, endOfMonth);
        return ResultVO.success(attendanceMapper.selectCount(queryWrapper));
    }

    @Override
    public Map<String, Object> getUserAttendanceRecords(Integer employeeId, int page, int size) {
        Page<Attendance> pageInfo = new Page<>(page, size);
        QueryWrapper<Attendance> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("employee_id", employeeId);
        Page<Attendance> result = this.page(pageInfo, queryWrapper);

        Map<String, Object> response = new HashMap<>();
        response.put("records", result.getRecords());
        response.put("total", result.getTotal());

        return response;
    }

    @Override
    public int clockIn(Integer attendanceId) {
        Attendance attendance = attendanceMapper.selectById(attendanceId);
        if (attendance != null && "未打卡".equals(attendance.getAttendanceStatus())) {
            attendance.setAttendanceStatus("出勤");
            attendance.setClockTime(new Date());
            return attendanceMapper.updateById(attendance);
        }
        return 0;
    }

    @Override
    public ResultVO getAttendanceEcharts() {
        LocalDate now = LocalDate.now();
        LocalDate startOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());
        LocalDate endOfMonth = now.with(TemporalAdjusters.lastDayOfMonth());
        QueryWrapper queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("attendance_status","缺勤");
        queryWrapper.between("created_at", startOfMonth, endOfMonth);
        QueryWrapper queryWrapper2 =new QueryWrapper<>();
        queryWrapper2.eq("attendance_status","出勤");
        queryWrapper2.between("created_at", startOfMonth, endOfMonth);
        QueryWrapper queryWrapper3 =new QueryWrapper<>();
        queryWrapper3.eq("attendance_status","请假");
        queryWrapper3.between("created_at", startOfMonth, endOfMonth);
        Long a= attendanceMapper.selectCount(queryWrapper);
        Long p= attendanceMapper.selectCount(queryWrapper2);
        Long l= attendanceMapper.selectCount(queryWrapper3);
        Map<String,Object> absence=new HashMap<>();
        absence.put("name","缺勤");
        absence.put("value",a);
        Map<String,Object> present=new HashMap<>();
        present.put("name","出勤");
        present.put("value",p);
        Map<String,Object> leave=new HashMap<>();
        leave.put("name","请假");
        leave.put("value",l);
        List<Map<String,Object>> attendanceCount = new ArrayList<>();
        attendanceCount.add(absence);
        attendanceCount.add(present);
        attendanceCount.add(leave);
        return ResultVO.success(attendanceCount,"获取三十天内打卡记录请求成功");
    }

    @Async
    public void updateAttendanceStatusAfterDelay(){
        try {
            Thread.sleep(5*60 * 1000); // 五分钟后执行
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        QueryWrapper queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("attendance_status","未打卡");
        // 获取所有状态为“未打卡”的记录
        List<Attendance> attendances = attendanceMapper.selectList(queryWrapper);
        for (Attendance attendance : attendances) {
            attendance.setAttendanceStatus("缺勤");
            attendanceMapper.updateById(attendance);
            System.out.println("更改了一个员工的打卡状态");
        }
    }

}




